package glemipsc.implementations.glemips32;

import glemipsc.Address;
import glemipsc.GLEMipsC;
import glemipsc.GLEMipsEmu;
import glemipsc.implementations.Argument;
import glemipsc.implementations.Instruction;

public class St extends Instruction {
	
	private int size;
	
	public St(Argument arg1, Address addr, int size) {
		arguments.add(arg1);
		arguments.add(addr.getSegment());
		arguments.add(addr.getOffset());
		this.size = size * 8;
	}
	
	@Override
	public String getOpCode() {
		String opcode;
		
		if (size == 8)
			opcode = Instruction.ST8;
		else if (size == 16)
			opcode = Instruction.ST16;
		else
			opcode = Instruction.ST32;
		
		opcode += arguments.get(1).getOpCode();
		opcode += arguments.get(0).getOpCode();
		opcode += arguments.get(2).getOpCode();
		return opcode + "\n";
	}

	@Override
	public String getName() {
		return "ST" + size;
	}

	@Override
	public void emulate(GLEMipsEmu emu) {
		int res;
		
		Register dest = (Register) arguments.get(0);
		Register base = (Register) arguments.get(1);
		int offset = ((Immediate) arguments.get(2)).n;
		res = dest.getEmulValue();
		if (size == 8)
			res = (res >> 24) | ((res >> 16) & 255) | ((res >> 8) & 255) | (res & 255);
		else if (size == 16)
			res = (res >> 16) | (res & 65535);
		emu.store(base.getEmulValue() + offset, res);
	}

}
